package source

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/PuerkitoBio/goquery"
)

const a9baseUrl = "http://bbs.a9vg.com/"

type A9vg struct {
}

func init() {
	registerType((*A9vg)(nil))
}

//get movie cover images url
func (J A9vg) FetchNews(url string) ([]NEWS, error) {
	println("query url :" + url)
	var newslist []NEWS
	// pageDoc, err := goquery.NewDocument(url)
	// if err != nil {
	// 	fmt.Println(err)
	// 	return newslist, err
	// }
	res, err := http.Get(url)
	if err != nil {
		return newslist, err
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		return newslist, errors.New("status code error: " + res.Status)
	}

	// Load the HTML document
	pageDoc, err := goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		return newslist, err
	}

	rootnode := pageDoc.Find("#moderate table")
	if len(rootnode.Nodes) <= 0 {
		return newslist, errors.New("can't find table")
	}
	fmt.Printf("news count: %d \n", len(rootnode.First().Find("tbody").Nodes))
	rootnode.First().Find("tbody").Each(func(i int, tr *goquery.Selection) {
		node := tr.Find("th.new a").First()

		item := NEWS{}
		if href, b := node.Attr("href"); b == true {
			item.Url = a9baseUrl + href
			item.Title = node.Text()
		} else {
			// fmt.Println(tr.Attr("id"))
			return
		}
		timenode := tr.Find("td.by em").First()
		if len(timenode.Nodes) > 0 {
			item.Time = timenode.Text()
		}
		authornode := tr.Find("td.by cite a").First()
		if len(timenode.Nodes) > 0 {
			item.Author = authornode.Text()
		}

		countnode := tr.Find("td.num em").First()
		if len(countnode.Nodes) > 0 {
			item.ReadCount = countnode.Text()
		}
		newslist = append(newslist, item)

	})

	return newslist, nil
}

//get movie cover images url
func (J A9vg) FetchNews_test(url string) ([]NEWS, error) {
	println("query url :" + url)
	var newslist []NEWS
	pageDoc, err := goquery.NewDocument(url)
	if err != nil {
		fmt.Println(err)
		return newslist, err
	}
	// Find the review items
	pageDoc.Find(".sidebar-reviews article .content-block").Each(func(i int, s *goquery.Selection) {
		// For each item found, get the band and title
		band := s.Find("a").Text()
		title := s.Find("i").Text()
		fmt.Printf("Review %d: %s - %s\n", i, band, title)
	})

	return newslist, nil
}
